package com.time.toupdate.Controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * paperYY
 * Author:B
 * http://127.0.0.1:8081/hi
 * http://localhost:8080/api/third_login/callback
 * http://t.csdnimg.cn/6W0Cx
 */
@RestController
@RequestMapping
@Slf4j
public class todoController {
    @GetMapping("/index")
    public String returnIndex() {
        return "主页";
    }

    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/callback")
    public String callback(@RequestParam("code") String code) {
        System.out.println(code);
//        根据code获得Token
//        https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("client_id", "8fb675e2a5b7a8dbc6a2f42022915c1e19296e4b0928f56574383bc34f839590");
        paramMap.put("client_secret", "d7bfe36693e6bc79b59610874cb3ee9ef60186750a2a7e4f96ff4431facb2933");
        paramMap.put("redirect_uri", "http://127.0.0.1:8080/callback");
        paramMap.put("code", code);
        paramMap.put("accept", "json");
        paramMap.put("grant_type", "authorization_code");
        String token = HttpUtil.post("https://gitee.com/oauth/token", paramMap);
        JSONObject parseObj = JSONUtil.parseObj(token);
        String access_token = parseObj.getStr("access_token");
        log.info("token是" + token);
        log.info("access_token" + access_token);
//        根据Token获取用户数据
        String data = HttpRequest.get("https://gitee.com/api/v5/user?access_token=" + access_token)
                .execute().body();
        log.info("data是" + data);
        UUID uuid = UUID.randomUUID();
        redisTemplate.opsForValue().set("hsq",data,1000*60, TimeUnit.MILLISECONDS);
        System.out.println("走了一圈后端");
//        拓展 数据存到mysql中
        return "success";
    }

    @GetMapping("/hi")
    public String sayhi() {
        return "hi!!!";
    }

}
